008. String to Integer (atoi) [E]


题目

Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

思路

这题也比较好做,关键是要考虑挺多东西,我也是提交了好多次才发现有这么多要考虑的地方。

  • 开头的空格
  • 正负符号的处理
  • 溢出处理
  • 非法输入

开头空格处理:

  1. while(str[i] == " ") i++;

正负号的处理:我觉得yuruofeifei这个解决方案简直赞

  1. if (str[i] == '-' || str[i] == '+') {
  2. sign = 1 - 2 * (str[i++] == '-');
  3. }
  4. ……
  5. return base * sign;

溢出处理(可以参考上一道题):

  1. if (base > INT_MAX / 10 || (base == INT_MAX / 10 && str[i] - '0' > INT_MAX%10)) {
  2. if (sign == 1) return INT_MAX;
  3. else return INT_MIN;
  4. }

非法输入:其实只用过滤就行了

  1. while (str[i] >= '0' && str[i] <= '9') {
  2. ……
  3. }

代码

我的代码,不够简洁,可以参考yuruofeifei的代码,在下面

  1. class Solution {
  2. public:
  3. int myAtoi(string str) {
  4. long tmp=0;
  5. bool neg;
  6. int i = 0;
  7. while(str[i] == ' ') i++; //读掉空格
  8. neg = str[i] == '-'?1:0;
  9. for(i = i+ (neg || str[i] == '+');i < str.length();i++) //如果是- 或 + i+1跳过符号
  10. {
  11. if(str[i] - '0' >= 0 && str[i] - '0' < 10) //过滤非法输入
  12. {
  13. tmp *= 10;
  14. tmp += (str[i] - '0');
  15. if(tmp >= INT_MAX && !neg) //溢出判断
  16. {
  17. tmp = INT_MAX;
  18. break;
  19. }
  20. if(tmp -1 >= INT_MAX && neg) //除了符号,INT_MAX和INT_MIN只差1
  21. {
  22. tmp = INT_MIN;
  23. break;
  24. }
  25. }
  26. else break;
  27. }
  28. if(neg) return -tmp;
  29. return tmp;
  30. }
  31. };

yuruofeifei的代码

  1. int myAtoi(string str) {
  2. int sign = 1, base = 0, i = 0;
  3. while (str[i] == ' ') { i++; }
  4. if (str[i] == '-' || str[i] == '+') {
  5. sign = 1 - 2 * (str[i++] == '-');
  6. }
  7. while (str[i] >= '0' && str[i] <= '9') {
  8. if (base > INT_MAX / 10 || (base == INT_MAX / 10 && str[i] - '0' > 7)) {
  9. if (sign == 1) return INT_MAX;
  10. else return INT_MIN;
  11. }
  12. base = 10 * base + (str[i++] - '0');
  13. }
  14. return base * sign;
  15. }